//
//  CLReadConfigure.swift
//  CJBookReader
//
//  Created by colin on 2019/3/21.
//  Copyright © 2019 lidi. All rights reserved.
//

import UIKit

class CLReadConfigure: Codable {
    
    /// 阅读最小阅读字体大小
    let minFontSize = 12
    /// 阅读最大阅读字体大小
    let maxFontSize = 25
    
    /// 当前阅读的背景颜色
    var colorIndex = 0 {didSet{save()}}
    
    /// 字体类型
    var fontType = CLFontType.system {didSet{self.save()}}
    
    /// 字体大小  默认为20
    var fontSize = 20 {didSet{self.save()}}
    
    /// 翻页效果
    var effectType = CLEffectType.simulation {didSet{self.save()}}
    
    /// 是夜间还是日间模式   true:夜间 false:日间
    var isNight = false {didSet{self.save()}}
    
    // MARK: -- 配置属性
    
    /// 背景颜色数组
    let readerBgColors:[UIColor] = [UIColor.readBg.day,
                               UIColor.readBg.byRefresh,
                               UIColor.readBg.eye,
                               UIColor.readBg.yellow]
    
    /// 根据背景颜色 对应的文字颜色 数组(数量必须与 readerBgColors 相同)
    let readerTextColors:[UIColor] = [UIColor.readText.day,
                                    UIColor.readText.byRefresh,
                                    UIColor.readText.eye,
                                    UIColor.readText.yellow]
    
    /// 根据背景颜色 对应的文字颜色 数组(数量必须与 readerBgColors and readerTextColors 相同)
    let readerHeaderAndFooterTextColors:[UIColor] = [UIColor.readHeaderAndFooterText.day,
                                                      UIColor.readHeaderAndFooterText.byRefresh, UIColor.readHeaderAndFooterText.eye,  UIColor.readHeaderAndFooterText.yellow]
    
    // MARK: -- 初始化，保存
    private static let kCLReadConfigureKey = "kCLReadConfigureKey"
    private static var instance:CLReadConfigure?
    static var shared:CLReadConfigure {
        if let instance_ = CLReadConfigure.instance {
            return instance_
        } else {
            do {
                if let data = CLUserDefaults.shared.object(key: CLReadConfigure.kCLReadConfigureKey) as? Data {
                    let decoder = JSONDecoder()
                    let config = try decoder.decode(CLReadConfigure.self, from: data)
                    instance = config
                    return config
                } else {
                    let config = CLReadConfigure()
                    instance = config
                    return config
                }
            } catch let error {
                print(error)
                let config = CLReadConfigure()
                instance = config
                return config
            }
        }
    }
    
    init() {}
  
    private func save() {
        do {
            let encoder = JSONEncoder()
            
            if #available(iOS 11.0, *) {
                encoder.outputFormatting = .sortedKeys
            } else {
                encoder.outputFormatting = .prettyPrinted
            }
            
            let data = try encoder.encode(self)
            CLUserDefaults.shared.set(object: data, key: CLReadConfigure.kCLReadConfigureKey)
        } catch let err {
            print(err)
        }
    }
    
    /// 清理(暂无需求使用)
    private func clear() {
        CLReadConfigure.instance = nil
        CLUserDefaults.shared.remove(key: CLReadConfigure.kCLReadConfigureKey)
    }
    
    private enum CodingKeys:String,CodingKey {
        case colorIndex
        case fontType
        case fontSize
        case effectType
        case isNight
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.colorIndex, forKey: .colorIndex)
        try container.encode(self.fontType, forKey: .fontType)
        try container.encode(self.fontSize, forKey: .fontSize)
        try container.encode(self.effectType, forKey: .effectType)
        try container.encode(self.isNight, forKey: .isNight)
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        for key in container.allKeys {
            switch key {
            case .colorIndex:
                self.colorIndex = try container.decodeNil(forKey: .colorIndex) ? 0 : try container.decode(Int.self, forKey: .colorIndex)
            case .fontType:
                self.fontType = try container.decodeNil(forKey: .fontType) ? CLFontType.system : try container.decode(CLFontType.self, forKey: .fontType)
            case .fontSize:
                self.fontSize = try container.decodeNil(forKey: .fontSize) ? 20 : try container.decode(Int.self, forKey: .fontSize)
            case .effectType:
                self.effectType = try container.decodeNil(forKey: .effectType) ? CLEffectType.simulation : try container.decode(CLEffectType.self, forKey: .effectType)
            case .isNight:
                self.isNight = try container.decodeNil(forKey: .isNight) ? false : try container.decode(Bool.self, forKey: .isNight)
            }
        }
    }
}

extension CLReadConfigure {
    
    /// 阅读文字颜色(需求自己选)
    var textColor:UIColor {
        
        // 固定颜色使用
        //return DZMColor_5
        
        // 根据背影颜色选择字体颜色(假如想要根据背景颜色切换字体颜色 需要在 configureBGColor() 方法里面调用 tableView.reloadData())
        if self.isNight {
            // 夜间
            return UIColor.readText.night
        } else {
            // 日间
            return self.readerTextColors[self.colorIndex]
        }
    }
    
    /// 获得文字属性字典
    var readAttribute: [NSAttributedString.Key:Any] {
        
        // 段落配置
        let paragraphStyle = NSMutableParagraphStyle()
        
        //首行缩进
        paragraphStyle.firstLineHeadIndent = CGFloat.readerSpace._3
        
        // 行间距
        paragraphStyle.lineSpacing = CGFloat.readerSpace._4
        
        // 段间距
        paragraphStyle.paragraphSpacing = CGFloat.readerSpace._6
        
        // 当前行间距(lineSpacing)的倍数(可根据字体大小变化修改倍数)
        paragraphStyle.lineHeightMultiple = 1.0
        
        // 对其
        paragraphStyle.alignment = NSTextAlignment.justified
        
        // 返回
        return [.foregroundColor:self.textColor,
                .font:self.readFont,
                .paragraphStyle:paragraphStyle]
    }
    
    /// 获得颜色
    var readColor: UIColor {
        if self.colorIndex == self.readerBgColors.firstIndex(of: UIColor.readBg.day) { // 牛皮黄
            let image = UIImage(named: "read_bg_0", in: Bundle(for: type(of: self)), compatibleWith: nil)
            return UIColor(patternImage:image!)
        } else {
            return self.readerBgColors[self.colorIndex]
        }
    }
    
    /// 获得阅读页头部和底部文字颜色
    var readHeaderAndFooterColor: UIColor {
        return self.readerHeaderAndFooterTextColors[self.colorIndex]
    }
    
    /// 获得文字Font
    var readFont: UIFont {
        if self.fontType == CLFontType.one { // 楷体
            return UIFont(name: "AmericanTypewriter-Light", size: CGFloat(self.fontSize))!
            //return UIFont(name: "EuphemiaUCAS-Italic", size: CGFloat(fontSize))! //黑体，暂时废弃
        }else if self.fontType == CLFontType.two { //宋体
            return UIFont(name: "Papyrus", size: CGFloat(self.fontSize))!
        } else { // 系统
            return UIFont.systemFont(ofSize: CGFloat(self.fontSize))
        }
    }
    
}
